/**
 * Created by liuzy on 2018/3/1.
 */
var configurationData = {
  exchanges: [{value: 1, name: "test", desc: "testdesc"}],
  symbols_types: [],
  supported_resolutions: [1, 5, 15, 30, 60,240, "D", "W"],
  supports_marks: true,
  supports_timescale_marks: true,
  supports_time: false
};
var Datafeeds = new Object();
Datafeeds.configurationData = configurationData;
Datafeeds.onRealtimeCallback = null;
Datafeeds.symbolInfo = {};
Datafeeds.url = {};
Datafeeds.websocket = {};
Datafeeds.systemTime=null;
Datafeeds.widget=null;

Datafeeds.onReady = function (e) {
  // console.log("onReady");
  e(this.configurationData);
};
Datafeeds.searchSymbols = function (userInput, exchange, symbolType, onResultReadyCallback) {
};
Datafeeds.initSymbolInfo = function () {
  var urlDatefee=window.location.href;
  //var urlDatefee=decodeURIComponent(window.location.href);
  var info_symbolId = commUtils.GetArgsFromHref(urlDatefee, "symbolKlineId");
  var info_symbolName = commUtils.GetArgsFromHref(urlDatefee, "symbolName");
  var info_precision = commUtils.GetArgsFromHref(urlDatefee, "scaleAmount");
  var has_volume = commUtils.GetArgsFromHref(urlDatefee, "hasVolume");
//  var info_symbolId = 25;
//  var info_symbolName = "TOPC-BTC01";
//  var info_precision = 8;
  this.symbolInfo.name = info_symbolName;
  this.symbolInfo.description = info_symbolName;
  this.symbolInfo.ticker = info_symbolId;
  this.symbolInfo.session = "24x7";
  this.symbolInfo.timezone = "Asia/Shanghai";
  this.symbolInfo.minmov = 1;
  this.symbolInfo.minmov2 = 0;
  this.symbolInfo.has_intraday = true;
  this.symbolInfo.has_daily = true;
  this.symbolInfo.has_empty_bars = true;
  this.symbolInfo.data_status = "streaming";
  this.symbolInfo.currency_code = "currency_code";
  this.symbolInfo.has_weekly_and_monthly=true;
  if(has_volume==1){
    this.symbolInfo.has_no_volume = true;
  }else{
    this.symbolInfo.has_no_volume = false;
  }
  this.symbolInfo.has_seconds = true;
  if (isEmpty(info_precision)) {
    info_precision = 8;
  }
  info_precision = parseInt(info_precision);
  var scale = 1;
  for (var i = 0; i < info_precision; i++) {
    scale = scale * 10;
  }
  this.symbolInfo.volume_precision = info_precision;
  this.symbolInfo.pricescale = scale;

}
Datafeeds.getBars = function (symbolInfo, resolution, from, to, onHistoryCallback, onErrorCallback, firstDataRequest) {
  var that = this;
  if (isEmpty(symbolInfo) || isEmpty(from) || isEmpty(symbolInfo.ticker)) {
    onErrorCallback("from or symbolInfo is null");
    return;
  }
  if (isEmpty(this.url.request)) {
    // console.log("please set url request");
    return;
  }
  // console.log("v2Kline form:"+from+",to:"+to);
  var param = null;
  param = {
    symbolId: symbolInfo.ticker,
    from: from * 1000,
    type: this.convertResolution(resolution)
  };
  if (firstDataRequest) {
    this.onHistoryCallback = onHistoryCallback;
  }else {
    param = $.extend(param, {to: to * 1000});
  }
  // console.log("getBars onHistoryCallback   param:"+param.since+","+param.endDate);
  $.ajax({
    url: this.url.request,
    data: param,
    type: "get",
    dataType: "json",
    success: function (data) {
      if (!isEmpty(data)) {
        /* try {
             data = isStringType(data);
             data = $.parseJSON(data);
         } catch (e) {
             console.log("datefee getbars historyData is error");
             Datafeeds.onHistoryCallback([], {noData: true});
             return;
         }*/
        if(data.code==0) {
          that.klineData=data.data;
          if (isEmpty(that.klineData)||that.klineData.length<=0) {
            Datafeeds.onHistoryCallback([], {noData: true});
            return;
          }
          that.klineData=Datafeeds.reversalData(that.klineData);
          Datafeeds.onHistoryCallback(that.klineData, {noData: false});
          if (firstDataRequest) {
            Datafeeds.lastKlineTime = that.klineData[that.klineData.length - 1].time;
            Datafeeds.bindWebsocket(Datafeeds.symbolInfo, resolution);
          }
        }else{
          Datafeeds.onHistoryCallback([], {noData: true});
          return;
        }
      }else{
        Datafeeds.onHistoryCallback([], {noData: true});
        return;
      }
    }
  });
};
Datafeeds.bindWebsocket = function (symbolInfo,resolution) {
  var type = this.convertResolutionToType(resolution);
  this.websocket.registerKey = "{'type':'" + type + "','symbol':'" + symbolInfo.ticker + "','contractType':'1'}";
  this.websocket.monitorKey = 'market' + type+ '_' + symbolInfo.ticker + '' + '_1';
  if (isEmpty(this.websocket.socket)&&!isEmpty(this.url.websocket)) {
    // console.log("&&&&&&&&&&&&&&&&&&&init socketsdfsdf ");
    this.websocket.socket = new webSocket('' + this.url.websocket + '');
  }
  if (!!this.websocket.socket) {
    if (isEmpty(this.websocket.registerKey) || isEmpty(this.websocket.monitorKey)) {
      return -1;
    }
    // console.log("bindWebsocket  "+this.websocket.registerKey +","+this.websocket.monitorKey);
    this.websocket.socket.emit('market', this.websocket.registerKey);
    this.websocket.socket.on('reconnect',function () {
      Datafeeds.reconnect(symbolInfo,resolution);
    });
    this.websocket.socket.on(this.websocket.monitorKey, function (binaryData) {
      var data = isStringType(binaryData);
      if (isEmpty(data)) {
        return -1;
      }
      var array = JSON.parse(data);
      var dataList=Datafeeds.convertWebsocketData(array);
      if(!isEmpty(dataList)){
        var length=dataList.length-1;
        for(var i=0;i<length+1;i++){
          var pushData=dataList[i];
          if(parseInt(pushData.time)>=Datafeeds.lastKlineTime) {
            Datafeeds.onRealtimeCallback(dataList[i]);
            Datafeeds.lastKlineTime=dataList[length].time;
          }
        }


      }
    });
  }
};

Datafeeds.reconnect=function(symbolInfo,resolution ,socket) {
  var that = this;
  var param = {
    symbolId: symbolInfo.ticker,
    from: Datafeeds.lastKlineTime,
    type: this.convertResolution(resolution)
  };
  $.ajax({
    url: this.url.request,
    data: param,
    type: "get",
    dataType: "json",
    success: function (data) {
      if(!isEmpty(data)&&!isEmpty(data.data)&&data.data.length>0){
        that.klineData=data.data;
        var length = that.klineData.length;
        for(var i=0; i<length; i++){
          var pushData = that.klineData[i];
          if(parseInt(pushData.time)>=Datafeeds.lastKlineTime) {
            Datafeeds.onRealtimeCallback(that.klineData[i]);
            Datafeeds.lastKlineTime=that.klineData[length-1].time;
          }
        }

      }
      Datafeeds.websocket.socket.emit('market', Datafeeds.websocket.registerKey);
    }
  });
};

Datafeeds.offerWebsocket=function () {
  // console.log("offerWebsocket  "+this.websocket.registerKey +","+this.websocket.monitorKey);
  if (!!this.websocket.socket) {
    if (isEmpty(this.websocket.registerKey) || isEmpty(this.websocket.monitorKey)) {
      return -1;
    }
    this.websocket.socket.off(this.websocket.monitorKey);//解除绑定原有的类型
    this.websocket.socket.off("reconnect");
    this.websocket.socket.emit('leaveMarket', this.websocket.registerKey);
  }
}
Datafeeds.convertWebsocketData = function (dataList) {
  if (isEmpty(dataList) || !(dataList instanceof Array)) {
    return null;
  }
  var converList = new Array();
  for (var i = 0; i < dataList.length; i++) {
    var data = dataList[i];
    var converdate = {time: data[0], close: Number(data[4]), open: Number(data[1]), high: Number(data[2]), low: Number(data[3]), volume: Number(data[5])};
    converList.push(converdate);
  }
  return converList;
}
Datafeeds.reversalData = function (dataList) {
  if (isEmpty(dataList) || !(dataList instanceof Array)) {
    return null;
  }
  var converList = new Array();
  var dataLength=dataList.length;
  for (var i = dataLength-1; i >=0; i--) {
    converList.push(dataList[i]);
  }
  return converList;
}

Datafeeds.convertResolution = function (resolution) {
  var klineType = "1min";
  if (resolution == 1) {
    klineType = "1min";
  } else if (resolution == 5) {
    klineType = "5min";
  } else if (resolution == 15) {
    klineType = "15min";
  } else if (resolution == 30) {
    klineType = "30min";
  } else if (resolution == 60) {
    klineType = "60min";
  } else if(resolution == 240){
    klineType = "4hour";
  } else if (resolution == "D") {
    klineType = "1day";
  } else if (resolution == "W") {
    klineType = "1week";
  }
  return klineType;
}
Datafeeds.convertResolutionToType = function (resolution) {
  var klineType = 0;
  if (resolution == 1) {
    klineType = 0;
  } else if (resolution == 5) {
    klineType = 1;
  } else if (resolution == 15) {
    klineType = 2;
  } else if (resolution == 30) {
    klineType = 9;
  } else if (resolution == 60) {
    klineType = 10;
  } else if(resolution == 240){
    klineType = 12;
  } else if (resolution == "D") {
    klineType = 3;
  } else if (resolution == "W") {
    klineType = 4;
  }
  return klineType;
}
function pollKlineData() {
  if (isEmpty(Datafeeds.symbolInfo) || isEmpty(Datafeeds.lastKlineTime) || isEmpty(Datafeeds.symbolInfo.ticker)) {
    return;
  }
  // console.log("poll request time" + Datafeeds.lastKlineTime);
  var param = {marketType: 0, symbol: Datafeeds.symbolInfo.ticker, since: Datafeeds.lastKlineTime, requestType: 1};
  var url = "/api/pollKline.do";
  $.ajax({
    url: url,
    data: param,
    type: "post",
    success: function (data) {
      if (!isEmpty(data)) {
        for (var i = 0; i < data.length; i++) {
          var pulldata = data[i];
          // console.log("poll data " + pulldata);
          if (i == data.length - 1) {
            // console.log("poll last time" + pulldata.time);
            Datafeeds.lastKlineTime = pulldata.time;
          }
          Datafeeds.onRealtimeCallback(pulldata);
        }
      }
    }
  });
}
Datafeeds.resolveSymbol = function (symbolName, onSymbolResolvedCallback, onResolveErrorCallback) {
  // console.log("resolveSymbol");
  onSymbolResolvedCallback(this.symbolInfo)
};
Datafeeds.subscribeBars = function (symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) {
  // console.log("subscribeBars");
  this.onRealtimeCallback = onRealtimeCallback;
  this.onResetCacheNeededCallback = onResetCacheNeededCallback;
  setCookieValue("trading"+this.symbolInfo.ticker,resolution);
  if(!isEmpty(this.widget)){
    var time=this.systemTime;
    if(!isEmpty(this.lastKlineTime)){
      time=parseInt(this.lastKlineTime);
    }
   /* var from1=time-this.intervalToTime(resolution);
    this.widget.chart().setVisibleRange({from:from1,to:time});*/
    /*let fromTime = this.klineData[this.klineData.length - 50].time / 1000;
    let toTime = this.klineData[this.klineData.length - 1].time / 1000;
    this.widget.chart().setVisibleRange({from: fromTime, to: toTime});*/
  }
}

// Datafeeds.intervalToTime=function(interval){
//   if(interval=="D"){
//     return 4406400 / 5;
//   }else if(interval==15){
//     return 194400  / 5;
//   }else if(interval==1){
//     return 16200  / 5;
//   }else if(interval==5){
//     return 63000  / 5;
//   }else if(interval==30){
//     return 346500  / 5;
//   }else if(interval==60){
//     return 898200  / 5;
//   }else if(interval=="W"){
//     return 2505600  / 5;
//   }
// }
Datafeeds.unsubscribeBars = function (subscriberUID) {
  // console.log("unsubscribeBars");
  this.offerWebsocket();
}
Datafeeds.calculateHistoryDepth = function (resolution, resolutionBack, intervalBack) {
  // console.log("calculateHistoryDepth " + resolution + "," + resolutionBack + "," + intervalBack);
  return "undefined";
}
Datafeeds.getMarks = function (symbolInfo, startDate, endDate, onDataCallback, resolution) {
  // console.log("getMarks ");
}
Datafeeds.getTimescaleMarks = function (symbolInfo, startDate, endDate, onDataCallback, resolution) {
  // console.log("getTimescaleMarks ");
}
Datafeeds.getServerTime = function (callback) {
  // console.log("getServerTime");
  if(configurationData.supports_time){
    $.ajax({
      url: this.url.systemTime,
      type: "get",
      success: function (data) {
        if(data.code == 0){
          var date;
          if(isEmpty(data.data)){
            date=new Date().getTime();
          }
          date=data.data.time;
          var date=parseInt(parseInt(date)/1000);
          callback(date);
          Datafeeds.systemTime=date;
        }
      }
    });
  }
}
Datafeeds.init = function () {
  this.initSymbolInfo();
}
Datafeeds.init();
